<?php
/**
 * Created by PhpStorm.
 * User: sunzexin
 * Date: 2017/12/22
 * Time: 14:58
 */

namespace App\Http\Logics\Admin;

use App\CafeEverydayRecommend;
use App\CafeMappingMark;
use App\CafeMappingUser;
use App\Partner;
use App\Photo;
use App\UserFollowCafe;
use App\Users;
use App\Video;
use Illuminate\Support\Collection;
use App\Cafe;
use Intervention\Image\Facades\Image;
use App\Http\Logics\BaseLogic;
class CafeLogic extends BaseLogic
{
    /**
     * 创建咖啡馆
     * @param $data 咖啡馆信息
     * @return mixed 创建结果
     */
    public static function createCafe($data)
    {
        try{
            // 获取咖啡馆名称的首个字母大写
            $cafe = new Cafe;
            $cafe->name = $data['name'];
            $pinyin = app('pinyin');
            $cafe->letter = strtoupper(substr($pinyin->sentence($data['name']), 0, 1));
            $cafe->address = $data['address'];
            $cafe->latlng = $data['latlng'];
            // 保存咖啡馆图片
            $photo_list_arr = json_decode($data['photo_list_str']);
            $cafe->cover = $photo_list_arr[0]->url;
//            $cafe->cover = $photo_list_arr[0].url;
            $cafe->save();

            $response = self::getUserIdByLoginSession($data['loginSession']);
            if ($response->code) {
                return self::response($response->code);
            }
            $user_id = $response->data;

            foreach ($photo_list_arr as $item){
                $url = $item->url."?imageInfo";
                // 处理图片
                $rs = dealHttp($url);
                $width = $rs->width;
                $height = $rs->height;
                $photo = new Photo();
                $photo->cafe_id = $cafe->id;
                $photo->url = $item->url;
                $photo->sort = $item->sort;
                $photo->width = $width;
                $photo->height = $height;
                $photo->user_id = $user_id;
                if (!$photo->save()){
                    return self::response(self::OBJECT_SAVE_FAIL);
                }
            }

            // 生成小程序二维码
            $page = 'pages/front/cafe/detail/detail';
            $response = self::getPartnerIdByLoginSession($data['loginSession']);
            if ($response->code) {
                return self::response($response->code);
            }
            $partner_id = $response->data;
            $response = self::createMiniProgressQrcodeUnlimit($partner_id, $page, $cafe->id);
            if ($response->code){
                return self::response($response->code);
            }
            $qrcode = $response->data;
            $cafe->qrcode = $qrcode;
            $response = self::getAddr($data['latlng']);
            if ($response->code){
                return self::response($response->code);
            }
            $address_component = $response->data;
            $cafe->citycode = $address_component->citycode;
            $cafe->adcode = $address_component->adcode;
            if(!$cafe->save()){
                return self::response(self::OBJECT_SAVE_FAIL);
            }

            $cafe_mapping_user = new CafeMappingUser();
            $cafe_mapping_user->user_id = $user_id;
            $cafe_mapping_user->cafe_id = $cafe->id;
            if(!$cafe_mapping_user->save()){
                return self::response(self::OBJECT_SAVE_FAIL);
            }

            $user = Users::find($user_id);
            if (empty($user)){
                return self::response(self::CONTENT_IS_EMPTY);
            }

            // 组装数据发送邀请通知
            $data_second = [
                'form_id' => $data['form_id'],
                'template_id' => 'TFDIwg22fJEwnUWfNbGMQpo_QYYTnDEO7uLVbig58b8',
                'touser' => $user->wx_app_openid,
                'keyword' => [
                    'keyword1' => [
                        'value' => '咖啡馆'.$cafe->name.'正在审核中',
                        'color' => '#000000'
                    ],
                    'keyword2' => [
                        'value' => '请到小程序中我的咖啡馆完善一下咖啡馆信息，审核通过会更快哦',
                        'color' => '#000000'
                    ]
                ],
                'page' => 'pages/admin/user/home/home'
            ];

            // 通过loginSession获取AccessToken
            $response = self::getAccessTokenByLoginSession($partner_id);
            if ($response->code) {
                return self::response($response->code);
            }
            $access_token = $response->data;

            $response = self::createNotify($data_second, $access_token);
            if ($response->code){
                return self::response($response->code);
            }

            return self::response(self::SUCCESS, $cafe);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 获取某个咖啡馆信息
     * @param $data 筛选的条件
     * @return mixed 返回结果
     */
    public static function getCafe($data)
    {
        try {
            if (!empty($data['loginSession'])) {
                $response = self::getPartnerIdByLoginSession($data['loginSession']);
                if ($response->code) {
                    return self::response(self::CONTENT_IS_EMPTY);
                }
                $partner_id = $response->data;
                $partner = Partner::find($partner_id);
                if (empty($partner)) {
                    return self::response(self::CONTENT_IS_EMPTY);
                }
            }
            $cafe = Cafe::find($partner->cafe_id);
            if (empty($cafe)) {
                return self::response(self::CONTENT_IS_EMPTY);
            }
            return self::response(self::SUCCESS, $cafe);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 获取附近多少公里内的咖啡馆
     * @param $cafe 要进行筛选的咖啡馆
     * @param $lat 用户所在位置纬度
     * @param $lng 用户所在位置经度
     * @param int distance 范围（公里）
     * @return mixed 附近的$distance范围内的咖啡馆
     */
    public static function getCafeByDistance($cafe, $lat, $lng, $distance = Cafe::DISTANCE)
    {
        try{
            $nearby_cafe_collection = new Collection();
            foreach ($cafe as $key => $item) {
                if (!empty($item->latlng)) {
                    $arr = explode(',', $item->latlng);
                    $cafe_lng = $arr[0];
                    $cafe_lat = $arr[1];
                    $dis = distance($lat, $lng, $cafe_lat, $cafe_lng);
                    $item->distance = $dis;
                    if ($dis < $distance)         //保留2公里内的咖啡馆
                    {
                        $nearby_cafe_collection->push($item);
                    }
                }
            }
            // 按距离排序
            $nearby_cafe_collection = $nearby_cafe_collection->sortBy('distance');
            $new_nearby_cafe = [];
            foreach ($nearby_cafe_collection as $item){
                array_push($new_nearby_cafe, $item);
            }
            return self::response(self::SUCCESS, $new_nearby_cafe);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 更新咖啡馆
     * @param $data 咖啡馆信息
     * @return mixed 返回更新结果
     */
    public static function updateCafe($data)
    {
//        try{
            $cafe = Cafe::find($data['cafe_id']);
            if (empty($cafe)) {
                return self::response(self::CONTENT_IS_EMPTY);
            }
            $cafe->since_year = $data['since_year'];
            $cafe->name = $data['name'];
            $pinyin = app('pinyin');
            $cafe->letter = strtoupper(substr($pinyin->sentence($data['name']), 0, 1));
            $cafe->address = $data['address'];
            $cafe->latlng = $data['latlng'];
            $cafe->logo = $data['logo'];
            // 生成小程序二维码
            $page = 'pages/front/cafe/detail/detail';
            $response = self::getPartnerIdByLoginSession($data['loginSession']);
            if ($response->code) {
                return self::response($response->code);
            }
            $partner_id = $response->data;
            $response = self::createMiniProgressQrcodeUnlimit($partner_id, $page, $cafe->id, $cafe->logo);
            if ($response->code){
                return self::response($response->code);
            }
            $qrcode = $response->data;
            $cafe->qrcode = $qrcode;
            $cafe->open_time = $data['open_time'];
            $cafe->close_time= $data['close_time'];
            $cafe->day_off = $data['day_off'];
            $cafe->outside_time = $data['outside_time'];
            $cafe->mobile = $data['mobile'];
            $cafe->summary = $data['summary'];
            $cafe->cover = $data['cover'];

            // 通过经纬度获取咖啡馆的详细地址信息
            $addressComponent = publicGetAddr($data['latlng']);
            $cafe->citycode = $addressComponent->citycode;
            $cafe->adcode = $addressComponent->adcode;
            $cafe->street = $addressComponent->streetNumber->street;
            if (!$cafe->save()){
                return self::response(self::OBJECT_SAVE_FAIL);
            }
            return self::response(self::SUCCESS);
//        }catch (\Exception $e){
//            return self::response(self::SYSTEM_ERROR);
//        }
    }

    /**
     * 获取推荐咖啡馆
     * @param $data 筛选条件
     * @return mixed 返回结果
     */
    public static function recommend($data)
    {
        try{
            $query = Cafe::with(['followedUser', 'mark'])->where(function ($query) use ($data){
                if ($data['star']){
                    $query->where('star', $data['star'])->where('status', 1);
                }
            })->orderBy('id', 'desc');
            $cafe = $data['limit'] ? $query->paginate($data['limit']) : $query->get();
            if (empty($cafe)){
                return self::response(self::CONTENT_IS_EMPTY);
            }

            // 判断是否分页
            $cafe_second = $data['limit'] ? $cafe->items() : $cafe;
            $response = self::getMoreCafeInfo($cafe_second);
            if ($response->code){
                return self::response($response->message);
            }

            if (empty($cafe)){
                return self::response(self::CONTENT_IS_EMPTY);
            }

            // 如果登录，则加上用户对每个咖啡馆的关注状态
            if (!empty($data['loginSession'])){
                $response = self::checkUserFollowCafe($data['loginSession'], $cafe_second);
                if ($response->code){
                    return self::response($response->code);
                }
            }

            return self::response(self::SUCCESS, $cafe);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 获取咖啡馆详情
     * @param $data
     * @return mixed
     */
    public static function getCafeDetail($data)
    {
        try{
            $cafe = Cafe::with(['followedUser' => function ($query){
                $query->orderBy('user_follow_cafe.id', 'desc');
            }, 'message' => function ($query){
                $query->orderBy('created_at', 'desc')->get()->take(6);
            }, 'user', 'mark', 'city', 'district', 'video'])->find($data['cafe_id']);
            if (empty($cafe)){
                return self::response(self::CONTENT_IS_EMPTY);
            }

            // 如果登录，则加上用户对每个咖啡馆的关注状态
            if (!empty($data['loginSession'])){
                $response = self::checkUserFollowCafe($data['loginSession'], $cafe);
                if ($response->code){
                    return self::response($response->code);
                }
            }

            $photo = $cafe->photo()->get();
            $photo = $photo->take(6);
            foreach ($photo as $item) {
                if(empty($item->width))
                {
                    $item->width=1;
                    $item->height=1;
                }
                $item->ratio=$item->width/$item->height;

                if($item->count()==6)
                    $item->ratio=1;
            }
            layout($photo);

            // 获取每个咖啡馆的图片
            $cafe->photo = $photo;
            // 获取咖啡馆的关注人数
            $cafe->followed_user_count = $cafe->followedUser()->count();
            // 获取咖啡馆的留言
            $cafe->message_count = $cafe->message()->count();

            if (empty($cafe)){
                return self::response(self::CONTENT_IS_EMPTY);
            }
            return self::response(self::SUCCESS, $cafe);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 获取咖啡馆列表
     * @param $data 筛选条件
     * @return mixed 返回结果
     */
    public static function getCafeList($data)
    {
//        try{
            $query = Cafe::with(['followedUser' => function ($query){
                $query->orderBy('id', 'desc');
            }, 'mark', 'city', 'district'])->where(function ($query) use ($data){
                if (isset($data['status']) && $data['status'] != ''){
                    $query->where('status', $data['status']);
                }
                if (isset($data['check_status']) && $data['check_status'] != ''){
                    $query->where('check_status', $data['check_status']);
                }
                if (isset($data['name']) && !empty($data['name'])){
                    $query->where('name', 'like', '%' . $data['name'] . '%');
                }
                if (isset($data['check_status']) && $data['star']){
                    $query->where('star', $data['star']);
                }
                if (isset($data['citycode']) && $data['citycode']){
                    $query->where('citycode', $data['citycode']);
                }
                if (isset($data['adcode']) && $data['adcode']){
                    $query->where('adcode', $data['adcode']);
                }
            })->orderBy('id', 'desc');

            // 标签过滤咖啡馆
            if (isset($data['mark_id_str']) && $data['mark_id_str']){
                $query = $query->whereHas('mark', function($query) use ($data){
                    $mark_id_arr = explode(',', $data['mark_id_str']);
                    $query->whereIn('mark.id', $mark_id_arr);
                });
            }

            $cafe = $data['limit'] ? $query->paginate($data['limit']) : $query->get();

            // 判断是否分页
            $cafe_second = $data['limit'] ? $cafe->items() : $cafe;
            $response = self::getMoreCafeInfo($cafe_second);
            if ($response->code){
                return self::response($response->code);
            }

            // 如果登录，则加上用户对每个咖啡馆的关注状态
            if (!empty($data['loginSession'])){
                $response = self::checkUserFollowCafe($data['loginSession'], $cafe_second);
                if ($response->code){
                    return self::response($response->code);
                }
            }

            $cafe->map(function ($cafe) {
                return $cafe->append('show_logo_bool')->append('status_bool');
            });
            if (empty($cafe)){
                return self::response(self::CONTENT_IS_EMPTY);
            }

            // 如果登录，则加上用户对每个咖啡馆的关注状态
            if (!empty($data['loginSession'])){
                // 判断是否分页
                $cafe_second = $data['limit'] ? $cafe->items() : $cafe;
                $response = self::checkUserFollowCafe($data['loginSession'], $cafe_second);
                if ($response->code){
                    return self::response($response->code);
                }
            }

            return self::response(self::SUCCESS, $cafe);
//        }catch (\Exception $e){
//            return self::response(self::SYSTEM_ERROR);
//        }
    }

    /**
     * 获取咖啡馆列表
     * @param $data 筛选条件
     * @return mixed 返回结果
     */
    public static function getLatestCafeList($data)
    {
        try{
            $query = Cafe::with(['followedUser' => function ($query){
                $query->orderBy('id', 'desc');
            }, 'mark', 'city', 'district'])->where(function ($query) use ($data){
                if ($data['status'] != ''){
                    $query->where('status', $data['status']);
                }
            })->orderBy('id', 'desc');
            $cafe = $data['limit'] ? $query->paginate($data['limit']) : $query->get();
            if (empty($cafe)){
                return self::response(self::CONTENT_IS_EMPTY);
            }

            // 判断是否分页
            $cafe_second = $data['limit'] ? $cafe->items() : $cafe;

            // 给咖啡馆加上图片
            $response = self::getMoreCafeInfo($cafe_second);
            if ($response->code){
                return self::response($response->message);
            }

            if (empty($cafe)){
                return self::response(self::CONTENT_IS_EMPTY);
            }

            // 如果登录，则加上用户对每个咖啡馆的关注状态
            if (!empty($data['loginSession'])){
                $response = self::checkUserFollowCafe($data['loginSession'], $cafe_second);
                if ($response->code){
                    return self::response($response->code);
                }
            }

            return self::response(self::SUCCESS, $cafe);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 设置咖啡馆状态
     * @param $data
     * @return mixed
     */
    public static function setCafeStatus($data)
    {
        try{
            $cafe = Cafe::find($data['cafe_id']);
            if (empty($cafe)){
                return self::response(self::CONTENT_IS_EMPTY);
            }
            $cafe->status = !$cafe->status;
            if (!$cafe->save()){
                return self::response(self::OBJECT_SAVE_FAIL);
            }
            return self::response(self::SUCCESS);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 设置咖啡馆LOGO状态
     * @param $data
     * @return mixed
     */
    public static function setShowLogo($data)
    {
        try{
            $cafe = Cafe::find($data['cafe_id']);
            if (empty($cafe)){
                return self::response(self::CONTENT_IS_EMPTY);
            }
            $cafe->show_logo = !$cafe->show_logo;
            if (!$cafe->save()){
                return self::response(self::OBJECT_SAVE_FAIL);
            }
            return self::response(self::SUCCESS);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 通过标签ID获取咖啡馆列表
     * @param $data 筛选条件
     * @return mixed 返回结果
     */
    public static function getCafeListByMarkId($data)
    {
        $query = Cafe::with(['followedUser', 'mark', 'city', 'district'])->where(function ($query) use ($data){
            if ($data['status']){
                $query->where('status', $data['status']);
            }
            if (isset($data['star']) && $data['star']){
                $query->where('star', $data['star']);
            }
        })->whereHas('mark', function ($query) use ($data){
            $query->where('mark.id', $data['mark_id']);
        })->orderBy('random');

        $cafe = $data['limit'] ? $query->paginate($data['limit']) : $query->get();
        if (empty($cafe)){
            return self::response(self::CONTENT_IS_EMPTY);
        }

        // 判断是否分页
        $cafe_second = $data['limit'] ? $cafe->items() : $cafe;
        $response = self::getMoreCafeInfo($cafe_second);
        if ($response->code){
            return self::response($response->message);
        }

        // 如果登录，则加上用户对每个咖啡馆的关注状态
        if (!empty($data['loginSession'])){
            // 判断是否分页
            $cafe_second = $data['limit'] ? $cafe->items() : $cafe;
            $response = self::checkUserFollowCafe($data['loginSession'], $cafe_second);
            if ($response->code){
                return self::response($response->code);
            }
        }

        return self::response(self::SUCCESS, $cafe);
    }

    /**
     * 获取咖啡馆的更多信息
     * @param $cafe
     * @return mixed
     */
    public static function getMoreCafeInfo($cafe)
    {
        foreach ($cafe as $item) {
            // 获取咖啡馆的关注人数
            $item->followed_user_count = $item->followedUser()->count();
            // 生成随机数
            $random_photos = ($item->id) % 6 + 1;
            // 获取每个咖啡馆的图片
            $photos = $item->photo()->get();
            $photos = $photos->take($random_photos);
            foreach ($photos as $photo) {
                if (empty($photo->width)) {
                    $photo->width = 1;
                    $photo->height = 1;
                }
                $photo->ratio = $photo->width / $photo->height;

                if ($photos->count() == 6)
                    $photo->ratio = 1;
            }

            $item->random_photos = $random_photos;
            layout($photos);
            $item->photos = $photos;
        }
        return self::response(self::SUCCESS);
    }

    /**
     * 更新咖啡馆WiFi
     * @param $data
     * @return mixed
     */
    public static function updateCafeWifi($data)
    {
        $response = self::getPartnerIdByLoginSession($data['loginSession']);
        if ($response->code){
            return self::response($response->code);
        }
        $partner_id = $response->data;

        $cafe = Cafe::where('partner_id', $partner_id)->first();
        if (empty($cafe)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        $cafe->wifi_ssid = $data['wifi_ssid'];
        $cafe->wifi_password = $data['wifi_password'];
        $cafe->wifi_bssid = $data['wifi_bssid'];
        if (!$cafe->save()){
            return self::response(self::SUCCESS);
        }
        return self::response(self::SUCCESS);
    }

    /**
     * 获取咖啡馆WiFi
     * @param $data
     * @return mixed
     */
    public static function getCafeWifi($data)
    {
        $response = self::getPartnerIdByKey($data['key']);
        if ($response->code){
            return self::response($response->code);
        }
        $partner_id = $response->data;

        $cafe = Cafe::where('partner_id', $partner_id)->select('wifi_ssid', 'wifi_password', 'wifi_bssid')->first();
        if (empty($cafe)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        return self::response(self::SUCCESS, $cafe);
    }

    /**
     * 判断用户是否关注咖啡馆
     * @param $loginSession 用户的验证秘钥
     * @param $cafe_second 咖啡馆列表
     * @return mixed
     */
    public static function checkUserFollowCafe($loginSession, $cafe_second)
    {
        $response = self::getUserIdByLoginSession($loginSession);
        if ($response->code) {
            return self::response($response->code);
        }
        $user_id = $response->data;

        if (count($cafe_second) > 1 || gettype($cafe_second) === 'array'){
            foreach ($cafe_second as $item) {
                // 判断咖啡馆的关注者是否为空，如果为空则直接判断该用户没有关注该咖啡馆
                if (empty($item->followedUser)){
                    $item->is_followed = UserFollowCafe::NOT_FOLLOWED;
                }else{
                    // 判断用户是否在关注者列表中
                    $followed_user_id_arr = array_column($item->followedUser->toArray(), 'id');
                    $item->is_followed = in_array($user_id, $followed_user_id_arr) ? UserFollowCafe::FOLLOWED : UserFollowCafe::NOT_FOLLOWED;
                }
            }
        }else{
            // 判断咖啡馆的关注者是否为空，如果为空则直接判断该用户没有关注该咖啡馆
            if (empty($cafe_second->followedUser)){
                $cafe_second->is_followed = UserFollowCafe::NOT_FOLLOWED;
            }else{
                $response = self::getUserIdByLoginSession($loginSession);
                if ($response->code) {
                    return self::response($response->code);
                }
                $user_id = $response->data;

                // 判断用户是否在关注者列表中
                $followed_user_id_arr = array_column($cafe_second->followedUser->toArray(), 'id');

                $cafe_second->is_followed = in_array($user_id, $followed_user_id_arr) ? UserFollowCafe::FOLLOWED : UserFollowCafe::NOT_FOLLOWED;
            }
        }
        return self::response(self::SUCCESS);
    }

    /**
     * 创建咖啡馆海报
     * @param $data
     */
    public static function createCafePoster($data)
    {
        $cafe = Cafe::find($data['cafe_id']);
        if (empty($cafe)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        // 创建画布
        $img = Image::canvas(600, 800, '#FFFFFF');
        // 判断咖啡馆是否有封面，如果没有，则读取第一张咖啡馆图片
        if (empty($cafe->cover)){
            $photo = Photo::where('cafe_id', $cafe->id)->first();
            if (empty($photo)){
                return self::response(self::CONTENT_IS_EMPTY);
            }
            $cover = $photo->url;
        }else{
            $cover = $cafe->cover;
        }
        $cover = downloadImage($cover.'?imageMogr2/auto-orient/thumbnail/500x350!');
        $qrcode = downloadImage($cafe->qrcode.'?imageMogr2/auto-orient/thumbnail/120x');
        $img->insert($cover, 'top-left', 50, 50);
        $img->insert($qrcode, 'bottom-right', 50, 35);
        $name_arr = ch2arr($cafe->name, 14);
        // 根据咖啡馆名称的长度调控咖啡馆名称字体大小
        $font_size = 48-count($name_arr)*6;
        $img->text($cafe->name, 50, 500, function($font) use ($font_size) {
            $font->file(public_path().'/font/weiruanyahei.ttf');
            $font->size($font_size);
            $font->color('#000000');
        });
        // 将使用过的图片从服务器本地移除
        removeImage($cover);
        removeImage($qrcode);
        if (!empty($cafe->since_year)){
            $img->text('since '.$cafe->since_year, 50, 710, function($font) {
                $font->file(public_path().'/font/weiruanyahei.ttf');
                $font->size(16);
                $font->color('#000000');
            });
            // 如果有since_year则地址往下一点
            $address_padding_top = 740;
        }else{
            // 如果没有since_year地址网上一点
            $address_padding_top = 720;
        }
        $address_arr = ch2arr($cafe->address, 22);
        foreach ($address_arr as $key => $item){
            $img->text($item, 50, $address_padding_top + (25*$key), function($font) {
                $font->file(public_path().'/font/weiruanyahei.ttf');
                $font->size(16);
                $font->color('#000000');
            });
        }
        $img->save('/temp/cafe-'.$cafe->id.'-poster.jpg', 60);
        $cafe_poster_url = uploadImage('/temp/cafe-'.$cafe->id.'-poster.jpg', 'cafe-poster');
        // 将图片从本地服务器删除
        removeImage('/temp/cafe-'.$cafe->id.'-poster.jpg');
        return self::response(self::SUCCESS, $cafe_poster_url);
    }

    /**
     * 创建所有咖啡馆的二维码
     * @param $data
     * @return mixed
     */
    public static function createCafeQrcodeOnce()
    {
        $cafe = Cafe::all();
        if (empty($cafe)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        foreach ($cafe as $item){
            errorLog($item->id);
            $response = self::createMiniProgressQrcodeUnlimit(1, 'pages/front/cafe/detail/detail', $item->id, $item->logo);
            if ($response->code){
                return self::response($response->code);
            }
            $qrcode = $response->data;
            $item->qrcode = $qrcode;
            if (!$item->save()){
                return self::response(self::OBJECT_SAVE_FAIL);
            }
        }
        return self::response(self::SUCCESS);
    }

    public static function getCafeLogo($data)
    {
        $query = Cafe::where(function ($query) use ($data){
            if ($data['show_logo'] != ''){
                $query->where('show_logo', $data['show_logo']);
            }
            if ($data['status'] != ''){
                $query->where('status', $data['status']);
            }
        })->orderBy('random');
        $cafe = $data['limit'] ? $query->paginate($data['limit']) : $query->get();
        if (empty($cafe)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        return self::response(self::SUCCESS, $cafe);
    }

    /**
     * 设置每日推荐
     */
    public static function setEverydayRecommend($data)
    {
        $cafe_everyday_recommend = new CafeEverydayRecommend();
        $cafe_everyday_recommend->cafe_id = $data['cafe_id'];
        $cafe_everyday_recommend->date = $data['date'];
        if (!$cafe_everyday_recommend->save()){
            return self::response(self::OBJECT_SAVE_FAIL);
        }
        return self::response(self::SUCCESS);
    }

    /**
     * 获取每日推荐列表
     * @param $data
     */
    public static function getEverydayRecommendList($data)
    {
        $cafe_everyday_recommend = CafeEverydayRecommend::orderBy('date', 'desc')->get();
        if (empty($cafe_everyday_recommend)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        foreach ($cafe_everyday_recommend as $item){
            $cafe = Cafe::find($item->cafe_id);
            if (empty($cafe)){
                return self::response(self::CONTENT_IS_EMPTY);
            }
            $item->title = $cafe->name;
        }
        return self::response(self::SUCCESS, $cafe_everyday_recommend);
    }

    /**
     * 获取每日推荐的咖啡馆
     * @param $data
     * @return mixed
     */
    public static function getEverydayRecommend($data)
    {
        $cafe_everyday_recommend = CafeEverydayRecommend::with(['cafe' => function ($query){
            $query->with(['followedUser' => function ($query){
                $query->orderBy('created_at', 'desc');
            }, 'user', 'mark']);
        }])->where(function ($query) use ($data){
            $query->where('date', strtotime($data['date']));
        })->first();
        if (empty($cafe_everyday_recommend)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        $photo = $cafe_everyday_recommend->cafe->photo()->get();
        $photo = $photo->take(6);
        foreach ($photo as $item) {
            if(empty($item->width))
            {
                $item->width=1;
                $item->height=1;
            }
            $item->ratio=$item->width/$item->height;

            if($item->count()==6)
                $item->ratio=1;
        }
        layout($photo);

        // 获取每个咖啡馆的图片
        $cafe_everyday_recommend->cafe->photo = $photo;
        // 获取咖啡馆的关注人数
        $cafe_everyday_recommend->cafe->followed_user_count = $cafe_everyday_recommend->cafe->followedUser()->count();
        // 获取咖啡馆的留言
        $cafe_everyday_recommend->cafe->message_count = $cafe_everyday_recommend->cafe->message()->count();
        return self::response(self::SUCCESS, $cafe_everyday_recommend);
    }

    /**
     * 获取咖啡馆图片
     * @param $data
     * @return mixed
     */
    public static function getCafePhoto($data)
    {
        $photo = Photo::where('cafe_id', $data['cafe_id'])->orderBy('sort')->get();
        if (empty($photo)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        return self::response(self::SUCCESS, $photo);
    }

    /**
     * 更新咖啡馆图片
     * @param $data
     * @return mixed
     * @throws \Exception
     */
    public static function updateCafePhoto($data)
    {
        $photos = Photo::where('cafe_id', $data['cafe_id'])->get();
        // 将之前与图文活动关联的图片删除掉
        foreach ($photos as $photo) {
            $photo->delete();
        }
        $photos_arr = json_decode($data['photo_list_str']);

        $response = self::getUserIdByLoginSession($data['loginSession']);
        if ($response->code) {
            return self::response($response->code);
        }
        $user_id = $response->data;

        foreach ($photos_arr as $key => $item) {
            $url = $item->url."?imageInfo";
            // 处理图片
            $rs = dealHttp($url);
            $width = $rs->width;
            $height = $rs->height;
            $photo = new Photo();
            $photo->cafe_id = $data['cafe_id'];
            $photo->url = $item->url;
            $photo->width = $width;
            $photo->height = $height;
            $photo->sort = $item->sort;
            $photo->user_id = $user_id;
            if (!$photo->save()) {
                return self::response(self::OBJECT_SAVE_FAIL);
            }
        }
        return self::response(self::SUCCESS);
    }

    public static function updateCafeMark($data)
    {
        $cafe_mapping_mark = CafeMappingMark::where('cafe_id', $data['cafe_id'])->get();

        // 删除掉之前的咖啡馆标签
        if (!empty($cafe_mapping_mark)){
            foreach ($cafe_mapping_mark as $item){
                if (!$item->delete()){
                    return self::response(self::OBJECT_DELETE_FAILD);
                }
            }
        }

        $mark_id_arr = explode(',', $data['mark_id_str']);
        foreach ($mark_id_arr as $mark_id){
            $cafe_mapping_mark = new CafeMappingMark();
            $cafe_mapping_mark->cafe_id = $data['cafe_id'];
            $cafe_mapping_mark->mark_id = $mark_id;
            if (!$cafe_mapping_mark->save()){
                return self::response(self::OBJECT_SAVE_FAIL);
            }
        }
        return self::response(self::SUCCESS);
    }


    /**
     * 审核咖啡馆
     * @param $data
     * @return mixed
     */
    public static function setCafePass($data)
    {
        $cafe = Cafe::find($data['cafe_id']);
        if (empty($cafe)){
            return self::response(self::CONTENT_IS_EMPTY);
        }

        if ($cafe === 5){
            return self::response(self::SET_CAFE_PASS_AGAIN);
        }

        $cafe->check_status = 5;
        if (!$cafe->save()){
            return self::response(self::OBJECT_SAVE_FAIL);
        }
        return self::response(self::SUCCESS);
    }

    /**
     * 删除每日推荐
     * @param $data
     */
    public static function deleteEverydayRecommend($data)
    {
        $cafe_everyday_recommend = CafeEverydayRecommend::where('cafe_id', $data['cafe_id'])->where('date', strtotime($data['date']))->first();
        if (empty($cafe_everyday_recommend)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        if (!$cafe_everyday_recommend->delete()){
            return self::response(self::OBJECT_DELETE_FAILD);
        }
        return self::response(self::SUCCESS);
    }

    /**
     * 创建咖啡馆视频
     * @param $data
     * @return mixed
     */
    public static function createCafeVideo($data)
    {
        $response = self::getUserIdByLoginSession($data['loginSession']);
        if ($response->code) {
            return self::response($response->code);
        }
        $user_id = $response->data;
        $video = new Video();
        $video->cafe_id = $data['cafe_id'];
        $video->url = $data['url'];
        $video->user_id = $user_id;
        if (!$video->save()){
            return self::response(self::OBJECT_SAVE_FAIL);
        }
        return self::response(self::SUCCESS, $video);
    }

    /**
     * 获取咖啡馆视频详情
     * @param $data
     * @return mixed
     */
    public static function getCafeVideoList($data)
    {
        if (isset($data['cafe_id']) && $data['cafe_id']){
            $video = Video::where('cafe_id' ,$data['cafe_id'])->orderBy('id', 'desc')->get();
        }else{
            if (isset($data['limit']) && $data['limit']){
                $query = Video::where(function ($query){
                    $query->where('status', 1);
                });
                $video = $data['limit'] ? $query->paginate($data['limit']) : $query->get();
            }
        }
        if (empty($video)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        return self::response(self::SUCCESS, $video);
    }

    public static function updateCafeVideo($data)
    {
        $video = Video::find($data['video_id']);
        if (empty($video)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        $video->url = $data['url'];
        if (!$video->save()){
            return self::response(self::OBJECT_SAVE_FAIL);
        }
        return self::response(self::SUCCESS);
    }

    /**
     * 删除咖啡馆视频
     * @param $data
     * @return mixed
     * @throws \Exception
     */
    public static function deleteCafeVideo($data)
    {
        $video = Video::find($data['video_id']);
        if (empty($video)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        if (!$video->delete()){
            return self::response(self::OBJECT_DELETE_FAILD);
        }
        return self::response(self::SUCCESS);
    }

    /**
     * 删除咖啡馆
     * @param $data
     * @return mixed
     * @throws \Exception
     */
    public static function deleteCafe($data)
    {
        $cafe = Cafe::find($data['cafe_id']);
        if (empty($cafe)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        if (!$cafe->delete()){
            return self::response(self::OBJECT_DELETE_FAILD);
        }
        return self::response(self::SUCCESS);
    }

    public static function getRecommendList($data)
    {
        $query = CafeEverydayRecommend::with(['cafe' => function ($query){
            $query->with(['followedUser' => function ($query){
                $query->orderBy('created_at', 'desc');
            }, 'user', 'mark', 'city']);
        }])->where(function ($query) use ($data){
            $query->where('date', '<=' , strtotime($data['date']));
        })->orderBy('date', 'desc');
        $cafe_recommend = $data['limit'] ? $query->paginate($data['limit']) : $query->get();
        if (empty($cafe_recommend)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        foreach ($cafe_recommend as $cafe){
            $photo = $cafe->cafe->photo()->get();
            $photo = $photo->take(6);
            foreach ($photo as $item) {
                if(empty($item->width))
                {
                    $item->width=1;
                    $item->height=1;
                }
                $item->ratio=$item->width/$item->height;

                if($item->count()==6)
                    $item->ratio=1;
            }
            layout($photo);

            // 获取每个咖啡馆的图片
            $cafe->cafe->photo = $photo;
            // 获取咖啡馆的关注人数
            $cafe->cafe->followed_user_count = $cafe->cafe->followedUser()->count();
            // 获取咖啡馆的留言
            $cafe->cafe->message_count = $cafe->cafe->message()->count();
        }
        return self::response(self::SUCCESS, $cafe_recommend);
    }

    public static function setCafeDefaultCover()
    {
        $cafe = Cafe::with(['photo'])->get();
        foreach ($cafe as $item){
            errorLog($item->photo->isEmpty());
            if (!empty($item->cover)){
                continue;
            }elseif($item->photo->isEmpty()){
                continue;
            }else{
                $item->cover = $item->photo->first()->url;
                if (!$item->save()){
                    return self::response(self::OBJECT_SAVE_FAIL);
                }
            }
        }
        return self::response(self::SUCCESS);
    }

    public static function changeShang($data)
    {
        $cafe_mapping_user = CafeMappingUser::where(function($query) use ($data){
            $query->where('user_id', $data['user_id']);
            $query->where('cafe_id', $data['cafe_id']);
        })->first();
        if (empty($cafe_mapping_user)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        $cafe_mapping_user->shang = !$cafe_mapping_user->shang;
        if (!$cafe_mapping_user->save()){
            return self::response(self::OBJECT_SAVE_FAIL);
        }
        return self::response(self::SUCCESS, $cafe_mapping_user->shang);
    }
}